package oss;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.UUID;

@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取文件
        Part p = request.getPart("file1");

        //生成文件名
        String fileName = UUID.randomUUID().toString();
        //获取文件后缀
        String suffix = getSuffix(p);

        //调用OSS工具类方法，上传文件到OSS服务器
        OSSUtil.upload(fileName + suffix, p.getInputStream());

        //保存文件路径到数据库
        String ossPath = "https://354-oss.oss-cn-guangzhou.aliyuncs.com/" + fileName + suffix;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * 获取文件后缀
     *
     * @param p
     * @return
     */
    private String getSuffix(Part p) {
        String content = p.getHeader("content-disposition");
        String[] arr = content.split(";");
        for (String str : arr) {
            if (str.trim().startsWith("filename")) {
                return str.substring(str.lastIndexOf("."), str.length() - 1);
            }
        }
        return "";
    }
}